package project.pianpian.controller;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import project.pianpian.entity.Tag;
import project.pianpian.entity.Video;
import project.pianpian.mapper.TagMapper;
import project.pianpian.mapper.VideoMapper;
import project.pianpian.utils.ReturnUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * description:
 * author :万霁初
 * date :2022/12/27 18:43
 **/
@RestController
@Slf4j
@RequestMapping("/main")
public class UploadPage {

    @Autowired
    VideoMapper videoMapper;
    @Autowired
    TagMapper tagMapper;

    //获取存储路径,从properties里拿
    @Value("${cover-save-path}")
    String coverPath;
    @Value("${video-save-path}")
    String videoPath;
    @Value("${demo-save-path}")
    String demoPath;

    //上传视频（这里的视频只用于放到首页供浏览，不用于订单）
    @PostMapping("/uploadVideo")
    public JSONObject uploadVideo(@RequestPart("uploaderId") String uploaderId,
                                  @RequestPart("title") String title,
                                  @RequestPart("cover") MultipartFile coverFile,
                                  @RequestPart("video") MultipartFile videoFile,
                                  @RequestParam("tags") String[] tagNames,
                                  HttpServletRequest request) throws Exception {

        if (title.equals("") || title == null || coverFile == null || videoFile == null) {
            return ReturnUtils.fail(406, "视频标题、封面以及视频文件本身不能为空");
        }
        if (tagNames.length==0){
            return ReturnUtils.fail(406,"视频必须带有至少一个标签");
        }


        String coverUri = upload(request, coverFile, coverPath, "cover");
        String videoUri = upload(request, videoFile, videoPath, "video");

        Video video = new Video(-1, Integer.parseInt(uploaderId), title, coverUri, videoUri, new Date());
        int result = videoMapper.insertVideo(video);
        if (result == 0) {
            return ReturnUtils.fail(500, "文件关联数据库失败");
        }

        Map map=new HashMap();
        map.put("video_uri",videoUri);
        List<Video> videos = videoMapper.selectByMap(map);
        Video video1 = videos.get(0);

        for (String tagName : tagNames) {
            Tag tag=new Tag(-1,video1.getId(),tagName);
            int result1 = tagMapper.insertTag(tag);

            if (result1==0){
                ReturnUtils.fail(500,"标签存入数据库失败");
            }

        }

        return ReturnUtils.success(201,"上传视频成功");

    }



    static String upload(HttpServletRequest request, MultipartFile multipartFile, String path, String type) throws Exception {

        if (!type.equals("cover") && !type.equals("video") && !type.equals("demo")) {
            throw new Exception("type必须指定正确的类型");
        }

        //判断文件是否为空
        if (multipartFile.isEmpty()) {
            throw new Exception("文件为空");
        }
//        //获取文件原名（包括后缀）
//        String originalFilename = multipartFile.getOriginalFilename();

        //设置日期格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("/yyyy.MM.dd/");
        //获取当前日期，格式为设置格式
        String nowDate = simpleDateFormat.format(new Date());
        //储存文件到path+nowDate,并取新的名字
        String realPath = path + nowDate;
        File file = new File(realPath);
        //以日期为分隔创建新文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        //给上传文件取新的名字，避免重名
        String newName = UUID.randomUUID().toString() + ".jpg";
        multipartFile.transferTo(new File(file, newName));

        //生成uri
        String uri = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/"+type+"s" +
                "" + nowDate + newName;

        //返回uri
        return uri;
    }
}